package cn.changeforyou.web.dao.mybatis.ext.extBuilder.writer;

import cn.changeforyou.base.exception.ExceptionFactory;
import cn.changeforyou.web.dao.mybatis.ext.exception.DaoExceptionEnum;
import cn.changeforyou.web.dao.mybatis.ext.extBuilder.SqlContext;
import cn.changeforyou.web.dao.mybatis.ext.extBuilder.builder.SelectBuilder;
import cn.changeforyou.web.dao.mybatis.ext.extBuilder.sqlUtils.WhereUtils;
import cn.changeforyou.web.dao.mybatis.ext.metaInfo.FieldMetaInfo;
import cn.changeforyou.web.dao.mybatis.ext.metaInfo.MappedStatementParameterType;
import cn.changeforyou.web.utils.tree.Tree;
import org.springframework.stereotype.Component;

/**
 * @author zhyu
 * @version 1.0
 * @date 2022/3/4 15:23
 */
@Component
public class WhereEntitySqlWriter extends AbstractSqlWriter {

    @Override
    void doWriteSql(SqlContext context) {
        MappedStatementParameterType mappedStatementParameterType = context.getMappedStatementParameterType();
        if (mappedStatementParameterType == MappedStatementParameterType.selectByEntity) {
           SqlBuilder sql = context.getSql();
            context.setScriptModel(true);
            sql.append(" <where>");
            Tree<String> whereTrees = context.getWhereTrees();
            for (Tree<String> node : whereTrees.getChildren()) {
                Object o = node.get(SelectBuilder.META_INFO);
                if (o instanceof FieldMetaInfo) {
                    FieldMetaInfo metaInfo = (FieldMetaInfo) o;
                    String columnName = metaInfo.getColumnName();
                    String fieldName = metaInfo.getFieldName();
                    Class fieldClass = metaInfo.getFieldClass();

                    WhereUtils.buildEasyIfTestScript(context,
                            columnName, fieldName,
                            fieldClass);
                }
            }
            sql.append(" </where>");
        } else {
            throw ExceptionFactory.jsonException(DaoExceptionEnum.CODE_ERROR);
        }
    }

    @Override
    public SentenceEnum getSentenceEnum() {
        return SentenceEnum.where;
    }
}
